package com.forlove.app.qselect.index.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseFragment;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.ParseHelper;
import com.forlove.app.common.widget.GuideWindow;
import com.forlove.app.common.widget.recyview.BaseRecyclerAdapter;
import com.forlove.app.common.widget.recyview.EndLessOnScrollListener;
import com.forlove.app.manager.DataManager;
import com.forlove.app.manager.FriendManager;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.qselect.MainTabView;
import com.forlove.app.qselect.index.adapter.FriendCircleAdapter;
import com.forlove.app.qselect.index.entity.FriendCircleInfoEntity;
import com.forlove.app.qselect.index.entity.PageEntity;
import com.forlove.app.qselect.index.presenter.FriendCircleInfoPresenter;
import com.forlove.app.qselect.index.view.FriendCircleInfoView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 我的好友fragment
 * Created by yjl on 2017/10/11.
 */

public class FriendCircleInfoFragment extends BaseFragment implements FriendCircleInfoView,
        SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.view_friend_recycler_view)
    RecyclerView friendRecyclerView;

    @BindView(R.id.view_refresh_index)
    SwipeRefreshLayout view_refresh_index;
    private FriendCircleAdapter friendCircleAdapter;
    public static boolean hasNewFriend = false;
    private ArrayList<FriendCircleInfoEntity> friendCircleEntities = new ArrayList<>();
    private List<FriendCircleInfoEntity> cacheFriendCircle = new ArrayList<>();
    private FriendCircleInfoPresenter friendCircleInfoPresenter;
    private boolean isloadingMore = false;//是否正在加载更多
    private boolean isRefresh = false;
    private Handler mHandler;

    private class CacheHandler extends Handler {
        public CacheHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 40000:
                    synchronized (friendCircleEntities) {
                        if (friendCircleEntities.size() == 0
                                && cacheFriendCircle.size() > 0
                                && friendCircleAdapter != null) {
                            friendCircleEntities.addAll(cacheFriendCircle);
                            friendCircleAdapter.updateDatas(friendCircleEntities);
                        }
                    }
                    break;
            }
        }
    }

    ;
    private static List<MainTabView.ActiveFlagListener> activeFlagListeners = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.fragment_friend_circle_info;
    }

    public static void setActiveFlagListener(MainTabView.ActiveFlagListener activeFlagListener) {
        if (activeFlagListener != null) {
            activeFlagListeners.add(activeFlagListener);
        }
    }

    @Override
    public void onSelected(int pos) {
        if (IndexFragment.getPos() == IndexFragment.POSITION_INDEX_FRIEND) {
            LogUtil.e("yjl", "onSelected FriendCircleInfoFragment");
            if (getView() == null && getActivity() != null) {
                mContext = getActivity();
                initFragmentView();
            } else if (!isInit && getView() != null) {
                mContext = getActivity();
                initFragmentView();
            } else if (isInit && getView() != null) {
                if (FriendCircleInfoFragment.hasNewFriend) {
                    requestFriendCircleInfo();
                }
            }
        }
    }

    @Override
    protected void initFragmentView() {
        if (!isInit && IndexFragment.getPos() == IndexFragment.POSITION_INDEX_FRIEND) {
            initFragment();
            isInit = true;
        }
    }

    private void showGuideView(View mainView) {
        if (mContext == null) {
            return;
        }
        boolean ishow = FriendManager.showFriendGuideView(mContext);
        if (ishow) {
            LinearLayout linearLayout = (LinearLayout) mContext.getLayoutInflater().
                    inflate(R.layout.layout_show_friend_guide, null);
            Display display = mContext.getWindowManager().getDefaultDisplay();
            linearLayout.setLayoutParams(new ViewGroup.LayoutParams(display.getWidth(), display.getHeight()));
            GuideWindow.Builder builder = new GuideWindow.Builder(getActivity());
            builder.setContentView(linearLayout);
            builder.showAtLocation(mainView, Gravity.CENTER, 0, 0);
            FriendManager.saveFriendGuideView(mContext, false);
        }
    }

    private void initCacheData() {
        HandlerThread thread = new HandlerThread("cacheTh");
        thread.start();
        Handler handler = new Handler(thread.getLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    String infoString = DataManager.getFriendCircleCache(getContext());
                    if (!TextUtils.isEmpty(infoString) && friendCircleEntities.size() == 0) {
                        List<FriendCircleInfoEntity> circleInfoEntities = ParseHelper.getModelList(infoString, "data.list", FriendCircleInfoEntity.class);
                        if (circleInfoEntities != null) {
                            cacheFriendCircle.addAll(circleInfoEntities);
                            CacheHandler cacheHandler = new CacheHandler(getContext().getMainLooper());
                            cacheHandler.sendEmptyMessage(40000);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


    }

    private void initFragment() {
        if (friendCircleInfoPresenter == null) {
            friendCircleInfoPresenter = new FriendCircleInfoPresenter(this);
        }
        view_refresh_index.setOnRefreshListener(this);
        view_refresh_index.setColorSchemeResources(R.color.common_green);
//        showGuideView(friendRecyclerView);
        if (!isInit) {
            initData();
        }
    }

    private void initData() {
        if (mHandler == null) {
            mHandler = new Handler();
        }

        if (friendCircleAdapter == null) {
            friendCircleAdapter = new FriendCircleAdapter(mContext, R.layout.item_friend_info,
                    friendCircleEntities, friendCircleInfoPresenter);
            friendRecyclerView.setAdapter(friendCircleAdapter);
            friendCircleAdapter.updateDatas(friendCircleEntities);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
            friendRecyclerView.setLayoutManager(linearLayoutManager);
            friendRecyclerView.addOnScrollListener(new EndLessOnScrollListener(linearLayoutManager) {
                @Override
                public void onLoadMore(int currentPage) {
                    if (!isloadingMore) {
                        isloadingMore = true;
                        friendCircleAdapter.showFootLoading();
                        friendCircleInfoPresenter.loadMoreFriendInfData();
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                friendCircleAdapter.hideFooterView();
                                isloadingMore = false;
                            }
                        }, 6000);
                    }
                }
            });

            friendCircleAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                    //TODO 好友详情
                    FriendCircleInfoEntity friendCircleInfoEntity = friendCircleEntities.get(position);
                    if (friendCircleInfoEntity.isread == 0) {
                        friendCircleInfoEntity.isread = 1;
                        friendCircleAdapter.notifyItemChanged(position);
                    }
                    Intent intent = new Intent(mContext, MineInfoActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("mobile", friendCircleInfoEntity.mTo);
                    intent.putExtras(bundle);
                    mContext.startActivity(intent);
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                    return false;
                }
            });
        }
        initCacheData();
        requestFriendCircleInfo();
    }


    private void requestFriendCircleInfo() {
        PageEntity pageEntity = new PageEntity();
        pageEntity.mPage = 1;
        pageEntity.mType = 1;
        if (friendCircleInfoPresenter != null) {
            isRefresh = true;
            friendCircleInfoPresenter.loadFriendInfoData(pageEntity);
        }
        for (MainTabView.ActiveFlagListener activeFlagListener : activeFlagListeners) {
            activeFlagListener.readFriendCircleInfo(false);
        }
    }

    @Override
    public void onRefresh() {
        //刷新
        if (!isRefresh) {
            requestFriendCircleInfo();
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isRefresh && view_refresh_index.isRefreshing()) {
                    view_refresh_index.setRefreshing(false);
                }
            }
        }, 6000);
    }

    @Override
    public void updateFriendCircleInfoView(PageEntity pageEntity, final List<FriendCircleInfoEntity> friendCircleEntities) {
        synchronized (this.friendCircleEntities) {
            isloadingMore = false;
            isRefresh = false;
            this.friendCircleEntities.clear();
            this.friendCircleEntities.addAll(friendCircleEntities);
            view_refresh_index.setRefreshing(false);
            friendCircleAdapter.hideFooterView();
            friendCircleAdapter.updateDatas(this.friendCircleEntities);
        }
    }

    @Override
    public void showErrorData(NetworkManager.ResultCode resultCode, String msg) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
        isloadingMore = false;
    }

    @Override
    public void onDestroy() {
        mHandler = null;
        activeFlagListeners.clear();
        super.onDestroy();
    }
}
